package com.sk.weichat.ui.account;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.makeramen.roundedimageview.RoundedImageView;
import com.sk.weichat.AppConstant;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.bean.LoginRegisterResult;
import com.sk.weichat.bean.User;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.UserDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.LoginHelper;
import com.sk.weichat.helper.PrivacySettingHelper;
import com.sk.weichat.sp.UserSp;
import com.sk.weichat.ui.MainActivity;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.lock.DeviceLockHelper;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.DeviceInfoUtil;
import com.sk.weichat.util.LiveDataBus;
import com.sk.weichat.util.Md5Util;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.SelectionFrame;
import com.umeng.analytics.MobclickAgent;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * @author lzs
 * @date 2019/9/19
 * Email:343067508@qq.com
 **/
public class MultiAccountActivity extends BaseActivity implements View.OnClickListener {
    private static final int pswd_incorrect = 1040326; //密码不正确的code ，跳转登录页面

    //切换账号成功事
    public static final String event_switch_account_success = "MultiAccountActivity_event_switch_account_success";
    private List<User> userList = new ArrayList<>();
    BaseQuickAdapter<User, BaseViewHolder> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multi_account);
        getSupportActionBar().hide();

        TextView tvTitle = findViewById(R.id.tv_title_center);
        tvTitle.setText(R.string.multi_account);

        findViewById(R.id.iv_title_left).setOnClickListener(this);
        findViewById(R.id.tv_add_account).setOnClickListener(this);
        findViewById(R.id.tv_logout).setOnClickListener(this);


        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new BaseQuickAdapter<User, BaseViewHolder>(R.layout.item_multi_account_user, userList) {

            @Override
            protected void convert(BaseViewHolder holder, User item) {
                holder.addOnClickListener(R.id.content, R.id.tv_delete);
                holder.setText(R.id.tv_name, item.getNickName());
                holder.setText(R.id.tv_id, "悦聊号：" + item.getAccount());
                RoundedImageView imageView = holder.getView(R.id.iv_avatar);
                AvatarHelper.getInstance().displayAvatar(item.getUserId(), imageView);
                if (item.isSelected()) {
                    holder.setVisible(R.id.iv_check, true);
                } else {
                    holder.setVisible(R.id.iv_check, false);
                }
            }
        };
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                User user = userList.get(position);
                //切换账号
                if (view.getId() == R.id.content) {
                    if (userList.get(position).getUserId().equals(coreManager.getSelf().getUserId())) {
                        return;
                    }
                    //重新登录
                    relogin(user);
                }
                if (view.getId() == R.id.tv_delete) {
                    if (userList.get(position).isSelected()) {
                        //退出当前账号
                        if (coreManager.getSelf().getHavePassword() == 0) {//未设置密码
                            showSetPasswordDialog();
                        } else {
                            showExitDialog();
                        }
                        return;
                    }
                    //删除其他该账号
                    if (UserDao.getInstance().deleteUser(userList.get(position)) && MultiAccountHelper.removeAccountID(mContext, userList.get(position).getUserId())) {
                        //删除账号成功
                        userList.remove(position);
                        adapter.notifyItemRemoved(position);
                        ToastUtil.showToast(mContext, getString(R.string.tips_delete_account_success));
                    } else {
                        //删除账号失败
                    }
                }
            }
        });

        recyclerView.setAdapter(adapter);
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                userList.clear();
                List<User> allUser = UserDao.getInstance().getAllUser();
                List<String> idList = MultiAccountHelper.getMultiAccountIDList(mContext);
                for (int i = 0; i < allUser.size(); i++) {
                    if (idList.contains(allUser.get(i).getUserId())) {
                        if (allUser.get(i).getUserId().equals(coreManager.getSelf().getUserId())) {
                            allUser.get(i).setSelected(true);
                        }
                        userList.add(allUser.get(i));
                    }
                }
                sort(userList);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void onLoginSuccess(User user) {
        //登录成功切换主账号,刷新recylerview
        int position = userList.indexOf(user);
        user.setSelected(true);
        adapter.notifyItemChanged(position);
        for (int i = 0; i < userList.size(); i++) {
            if (!userList.get(i).getUserId().equals(userList.get(position).getUserId()) && userList.get(i).isSelected()) {
                userList.get(i).setSelected(false);
                adapter.notifyItemChanged(i);
            }
        }
        sort(userList);
        adapter.notifyItemMoved(position, 0);
    }


    private void relogin(User user) {
        DialogHelper.showMessageProgressDialog(mContext, "正在切换账户");
        Map<String, String> params = new HashMap<>();
        String md5phone = PreferenceUtils.getString(mContext, user.getUserId());
//        Log.e("lzs", "phone :" + md5phone);
//        Log.e("lzs", "password :" + user.getPassword());
        params.put("telephone", md5phone);          // 账号登录的时候需要MD5加密，服务器需求
        params.put("password", user.getPassword());
        params.put("xmppVersion", "1");
        // 附加信息+
        params.put("model", DeviceInfoUtil.getModel());
        params.put("osVersion", DeviceInfoUtil.getOsVersion());
        params.put("serial", DeviceInfoUtil.getDeviceId(mContext));
        // 地址信息
        double latitude = MyApplication.getInstance().getBdLocationHelper().getLatitude();
        double longitude = MyApplication.getInstance().getBdLocationHelper().getLongitude();
        if (latitude != 0)
            params.put("latitude", String.valueOf(latitude));
        if (longitude != 0)
            params.put("longitude", String.valueOf(longitude));

        if (MyApplication.IS_OPEN_CLUSTER) {// 服务端集群需要
            String area = PreferenceUtils.getString(this, AppConstant.EXTRA_CLUSTER_AREA);
            if (!TextUtils.isEmpty(area)) {
                params.put("area", area);
            }
        }
        HttpUtils.get().url(coreManager.getConfig().USER_SWITCH_LOGIN)
                .params(params)
                .build()
                .execute(new BaseCallback<LoginRegisterResult>(LoginRegisterResult.class) {

                    @Override
                    public void onResponse(com.xuan.xuanhttplibrary.okhttp.result.ObjectResult<LoginRegisterResult> result) {
                        if (result.getResultCode() == 1) {
                            boolean success = LoginHelper.setLoginUser(mContext, coreManager, user.getTelephone(), user.getPassword(), result);
                            if (success) {
                                FriendDao.getInstance().checkSystemFriend(coreManager.getSelf().getUserId()); // 检查 两个公众号
                                PreferenceUtils.putBoolean(MultiAccountActivity.this, Constants.LOGIN_CONFLICT, false);// 重置登录冲突记录
                                LoginRegisterResult.Settings settings = result.getData().getSettings();
                                MyApplication.getInstance().initPayPassword(result.getData().getUserId(), result.getData().getPayPassword());
                                PrivacySettingHelper.setPrivacySettings(MultiAccountActivity.this, settings);
                                onLoginSuccess(user);
                                //耗时操作
                                coreManager.logout();
                                Constants.IS_CLOSED_ON_ERROR_END_DOCUMENT = true;// 将该标志位置为true，这样当CoreService调用init()方法时，才用调用init()方法内的release(将所有xmpp有关对象清空重构)
                                coreManager.relogin();
                                coreManager.autoReconnect(getApplicationContext());
                                //发送事件
                                LiveDataBus.get().with(event_switch_account_success).postValue("");
                                DialogHelper.dismissProgressDialog();
                                ToastUtil.showToast(mContext, getString(R.string.tips_switch_account_success));
                            } else { //  登录出错 || 用户资料不全
                                DialogHelper.dismissProgressDialog();
                                String message = TextUtils.isEmpty(result.getResultMsg()) ? getString(R.string.tip_incomplete_information) : result.getResultMsg();
                                ToastUtil.showToast(mContext, message);
                            }
                        } else if (result.getResultCode() == pswd_incorrect) {
                            DialogHelper.dismissProgressDialog();
                            startActivity(new Intent(mContext, LoginActivity.class));
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        } else {
                            DialogHelper.dismissProgressDialog();
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(mContext);
                    }
                });

    }

    private void logTime(int pos) {
        Log.e("lzs", pos + "  time:" + System.currentTimeMillis());
    }

    private void sort(List<User> list) {
        Collections.sort(list, new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                return o1.isSelected() ? -1 : o2.isSelected() ? 1 : 0;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_add_account:
                MultiAccountHelper.setAddAccountFlag(true);
                MainActivity.isRelogin = true;
                //添加或者创建新账号
                coreManager.logout();
                Constants.IS_CLOSED_ON_ERROR_END_DOCUMENT = true;// 将该标志位置为true，这样当CoreService调用init()方法时，才用调用init()方法内的release(将所有xmpp有关对象清空重构)
                startActivity(new Intent(mContext, SMSLoginActivity.class));
                break;
            case R.id.iv_title_left:
                //
                finish();
                break;

            case R.id.tv_logout:
                //退出当前账号
                // 退出账号
                if (coreManager.getSelf().getHavePassword() == 0) {//未设置密码
                    showSetPasswordDialog();
                } else {
                    showExitDialog();
                }
                break;
        }
    }

    // 去设置密码
    private void showSetPasswordDialog() {
        SelectionFrame setPasswordDialog = new SelectionFrame(this);
        setPasswordDialog.setSomething(getString(R.string.dialog_title), getString(R.string.sure_set_password), "暂不设置", "确定", new SelectionFrame.OnSelectionFrameClickListener() {
            @Override
            public void cancelClick() {//做退出账号操作
                showExitDialog();
            }

            @Override
            public void confirmClick() {
                Intent intent = new Intent(mContext, SetPasswordActivity.class);
                intent.putExtra("from", SetPasswordActivity.SET_FROM_NEW);
                startActivity(intent);
            }
        });
        setPasswordDialog.show();
//        final WindowManager.LayoutParams params = setPasswordDialog.getWindow().getAttributes();
//        params.width = DisplayUtil.dip2px(this,256);
//        setPasswordDialog.getWindow().setAttributes(params);
    }

    // 退出当前账号
    private void showExitDialog() {
        SelectionFrame mSF = new SelectionFrame(this);
        mSF.setSomething(getString(R.string.dialog_title), getString(R.string.sure_exit_account), new SelectionFrame.OnSelectionFrameClickListener() {
            @Override
            public void cancelClick() {

            }

            @Override
            public void confirmClick() {
                //y友盟登出
                MultiAccountHelper.setAddAccountFlag(false);
                MobclickAgent.onProfileSignOff();
                logout();
                //UserDao.getInstance().deleteAllUser();
                // 退出时清除设备锁密码，
                DeviceLockHelper.clearPassword();
                UserSp.getInstance(mContext).clearUserInfo();
                MyApplication.getInstance().mUserStatus = LoginHelper.STATUS_USER_SIMPLE_TELPHONE;
                coreManager.logout();
                LoginHelper.broadcastLogout(mContext);
                startActivity(new Intent(mContext, SMSLoginActivity.class));
                finish();
            }
        });
        mSF.show();
//        final WindowManager.LayoutParams params = mSF.getWindow().getAttributes();
//        params.width = DisplayUtil.dip2px(this,256);
//        mSF.getWindow().setAttributes(params);
    }

    private void logout() {
        HashMap<String, String> params = new HashMap<String, String>();
        // 得到电话
        String phoneNumber = coreManager.getSelf().getTelephone();
        // 去掉区号,
        String mobilePrefix = String.valueOf(PreferenceUtils.getInt(MyApplication.getContext(), Constants.AREA_CODE_KEY, 86));
        String phoneNumberRel;
        if (phoneNumber.startsWith(mobilePrefix)) {
            phoneNumberRel = phoneNumber.substring(mobilePrefix.length());
        } else {
            phoneNumberRel = phoneNumber;
        }
        String digestTelephone = Md5Util.toMD5(phoneNumberRel);
        params.put("telephone", digestTelephone);
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        // 默认为86
        params.put("areaCode", String.valueOf(86));
        params.put("deviceKey", "android");

        HttpUtils.get().url(coreManager.getConfig().USER_LOGOUT)
                .params(params)
                .build()
                .execute(new BaseCallback<String>(String.class) {

                    @Override
                    public void onResponse(ObjectResult<String> result) {
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                    }
                });
    }

    @Override
    protected void onResume() {
        MainActivity.isRelogin = false;
        super.onResume();
    }
}
